// yb_shop/pages/poster/index.js
var app = getApp();
let wechat = require("../..//utils/wechat.js");
var core = require("../..//utils/core.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    src: '',
    paths: {
      goods: 'yb_mingpian/pages/goods/detail/index',
      msgoods: 'yb_mingpian/pages/miaosha/seckillGoods/index',
      kjgoods: 'yb_mingpian/pages/kanjia/goods_info/index',
      ptgoods: 'yb_mingpian/pages/pintuan/pages/goods/detail',
    },
    config:app.config,
      show_rec: 0
  },

  dosave: function () {
    if (this.data.src.length > 0) {
      wx.showLoading({ title: '保存中...' });
      wechat.saveImageToPhotosAlbum(this.data.src).then(d => {
        wx.hideLoading();
        core.alert("海报保存成功");
      }).catch(e => {
        wx.hideLoading();
        core.alert("海报保存失败,请重试");
      })
    }
    else {
      core.alert("海报正在生成,请稍候");
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      var that = this;
    console.log("options", options);
    var path = this.data.paths[options.share_type];
    var id = options.id;

      that.setData({
        show_rec: options.show_rec != undefined ? options.show_rec : 0
      })

    var pic_url = app.util.makeurl({
      url: 'entry/wxapp/net_img', data: {
        url: encodeURIComponent(options.img)
      }
    });

    options.img = pic_url;

    console.log("options",options);
    core.loading('海报生成中');
    const ctx = wx.createCanvasContext('poster');
    ctx.clearRect(0, 0, 0, 0);

    ctx.setFillStyle('#ffffff')
    ctx.fillRect(0, 0, 750, 1060) // x, y, width, height

    if (that.data.show_rec == 1) {
        // 用户推荐显示
        const USER_NAME_LENGTH = 12;  // 正文 单行显示字符长度
        let [textLeng, textArray, textRows] = this.textByteLength(app.getCache('userinfo').nickName, USER_NAME_LENGTH);
        ctx.setTextAlign('left')
        ctx.setFontSize('28');
        ctx.setFillStyle("#333333");
        console.log("textArray",textArray);
        if (textArray.length == 1) {
            ctx.fillText(textArray[0], 100, 805);
        } else {
            ctx.fillText(textArray[0] + '...', 100, 805);
        }

        ctx.setFontSize('40');
        ctx.setFillStyle("#333333");
        ctx.fillText("为你推荐", 300, 805);

        var price_height = 875;
        var minus_height = 0;
    } else {
        var price_height = 825;
        var minus_height = 20;
    }

    // 商品名称显示
    const CONTENT_ROW_LENGTH = 32;  // 正文 单行显示字符长度
    let [contentLeng, contentArray, contentRows] = this.textByteLength(options.title, CONTENT_ROW_LENGTH);
    ctx.setTextAlign('left')
    ctx.setFontSize('28');
    ctx.setFillStyle("#333333");
    let contentHh = 35;
    let original_price_height = 930;
    for (let m = 0; m < contentArray.length; m++) {
      if (m == 1){
        original_price_height = 950;
        ctx.fillText(contentArray[m] + '...', 30, price_height + contentHh * m);
        break;
      } else {
        ctx.fillText(contentArray[m], 30, price_height + contentHh * m);
      }
    }

    var price = "原价￥" + (options.original_price);
    ctx.setFontSize('22');
    ctx.setFillStyle("#818181");
    ctx.fillText(price, 32, original_price_height - minus_height);//原价
    const metrics = ctx.measureText(price);

    ctx.setFontSize('22');
    ctx.setFillStyle("#333333");
    ctx.fillText("优惠价￥", 32, 1000);
    ctx.fillText("长按识别二维码", 530, 1000);

    ctx.setFontSize(48);
    ctx.setFillStyle("#d92d20");
    ctx.fillText(options.price, 120, 1000);

    // 划线
    // ctx.setStrokeStyle("#818181")
    // ctx.beginPath()
    // ctx.setLineWidth(1)
    // ctx.moveTo(32, 911)
    // ctx.lineTo(metrics.width + 32, 911)
    // ctx.stroke()

    var url = app.util.makeurl({
      url: 'entry/wxapp/qr_code', data: {
        path: path,
        scene: id,
        pid: app.getCache('userinfo').uid,
        card_id: app.globalData.card_id
      }
    });
    console.log("url",url);
    var md5 = app.util.md5("share_type=" + options.share_type + "&id=" + options.id);
    var qrcode_path = app.getCache(md5);
    console.log("qrcode_path",qrcode_path);

    if (qrcode_path != "") {
      console.log("has save !!!!!!!");
      // (图片资源, 图像的左上角在目标canvas上x轴的位置, 图像的左上角在目标canvas上y轴的位置,绘制图像的宽度,绘制图像的高度)
      ctx.drawImage(qrcode_path, 510, 765, 200, 200);
      wechat.downloadFile(options.img)
        .then(d => {
          ctx.drawImage(d.tempFilePath, 0, 0, 750, 750);
          if (that.data.show_rec == 1) {
              return wechat.downloadFile(app.getCache('userinfo').avatarUrl);
          }
        })
        .then(d => {
          console.log(d);
            if (that.data.show_rec == 1) {
                ctx.drawImage(d.tempFilePath, 30, 765, 60, 60)
            }

          ctx.draw(false, function () {
          setTimeout(() => {
            wx.canvasToTempFilePath({
              destWidth: 750,
              destHeight: 1060,
              canvasId: 'poster',
              success: function (res) {
                core.hideLoading();
                console.log(res.tempFilePath)
                that.setData({
                  src: res.tempFilePath
                });
              }
            });
          }, 150)
          });
        })
        .catch(err => {
          core.alert("商品图片无法下载,海报生成失败");
        })
    } else {
      console.log("not save !!!!!!!");

      if (that.data.show_rec == 1) {
          wechat.downloadFile(options.img)
              .then(d => {
                  console.log("good_img", d);
                  ctx.drawImage(d.tempFilePath, 0, 0, 750, 750);
                  return wechat.downloadFile(app.getCache('userinfo').avatarUrl);
              })
              .then(d => {
                  console.log("user_img", d);

                  // 圆角
                  // ctx.save()
                  // ctx.beginPath()
                  // ctx.arc(30, 805, 50, 0, 2 * Math.PI);
                  // ctx.clip()
                  // ctx.drawImage(d.tempFilePath, 10, 805, 136, 136)
                  // ctx.restore()
                  // ctx.draw()
                  ctx.drawImage(d.tempFilePath, 30, 765, 60, 60)
                  return wechat.downloadFile(url);
              })
              .then(d => {
                  console.log("qr_img", d);
                  return wechat.saveFile(d.tempFilePath);
              })
              .then(d => {
                  var savedFilePath = d.savedFilePath;
                  app.setCache(md5, savedFilePath);
                  ctx.drawImage(savedFilePath, 510, 765, 200, 200);

                  ctx.draw(false, function () {
                      setTimeout(() => {
                          wx.canvasToTempFilePath({
                              destWidth: 750,
                              destHeight: 1060,
                              canvasId: 'poster',
                              success: function (res) {
                                  console.log(res)
                                  core.hideLoading();
                                  that.setData({
                                      src: res.tempFilePath
                                  });
                              }
                          })
                      }, 150)
                  });
              })
              .catch(err => {
                  core.alert("商品图片无法下载,海报生成失败");
              })
      } else {
          wechat.downloadFile(options.img)
              .then(d => {
                  console.log("good_img", d);
                  ctx.drawImage(d.tempFilePath, 0, 0, 750, 750);
                  return wechat.downloadFile(url);
              })
              .then(d => {
                  console.log("qr_img", d);
                  return wechat.saveFile(d.tempFilePath);
              })
              .then(d => {
                  var savedFilePath = d.savedFilePath;
                  app.setCache(md5, savedFilePath);
                  ctx.drawImage(savedFilePath, 510, 765, 200, 200);

                  ctx.draw(false, function () {
                      setTimeout(() => {
                          wx.canvasToTempFilePath({
                              destWidth: 750,
                              destHeight: 1060,
                              canvasId: 'poster',
                              success: function (res) {
                                  console.log(res)
                                  core.hideLoading();
                                  that.setData({
                                      src: res.tempFilePath
                                  });
                              }
                          })
                      }, 150)
                  });
              })
              .catch(err => {
                  core.alert("商品图片无法下载,海报生成失败");
              })
      }
    }

  },

  textByteLength: function (text, num) {  // text为传入的文本  num为单行显示的字节长度
    let strLength = 0; // text byte length
    let rows = 1;
    let str = 0;
    let arr = [];
    for (let j = 0; j < text.length; j++) {
      if (text.charCodeAt(j) > 255) {
        strLength += 2;
        if (strLength > rows * num) {
          strLength++;
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      } else {
        strLength++;
        if (strLength > rows * num) {
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      }
    }
    arr.push(text.slice(str, text.length));
    return [strLength, arr, rows]   //  [处理文字的总字节长度，每行显示内容的数组，行数]
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})